
import 'dart:async';
import 'package:audio_session/audio_session.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../im/chatPage.dart';
import '../../../im/groupchat.dart';
import '../../../network/Api.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/provider.dart';
import '../../../widget/icon_text.dart';
import 'message_list_controller.dart';

class MessageData extends StatefulWidget {
  EMConversation emMessage;

  MessageData(this.emMessage, {Key? key}) : super(key: key);

  @override
  State<MessageData> createState() => _MessageDataState();
}

class _MessageDataState extends State<MessageData> {
  var _regExp = r"^[a-z0-9_]+$";
  Map _userInfo = {};
  late EMMessage emmessage;
  String content = "";
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();
  late StreamSubscription _recorderSubscription;
  late StreamSubscription _playerSubscription;
  final player = AudioPlayer();
  late EMTextMessageBody textBody;
  late EMMessageBody? body;
  late EMVoiceMessageBody voiceBody;
  late EMImageMessageBody imageBody;
  late EMVideoMessageBody videoBody;

  MessageListController messageListController =Get.put(MessageListController());

  String membersex = "";
  int time = 0;
  String dateTime = '';
  int unReadCont=0;

  @override
  void initState() {
    super.initState();
    widget.emMessage.unreadCount().then((value){
      unReadCont=value;
    });
    _getMessagesInfo();
    _getMemberInfo();
    _addChatListener();
    _getServeTime();

  }

  @override
  void dispose() {
    super.dispose();
    EMClient.getInstance.chatManager.removeEventHandler("YXA6hl6vye2MTQOb2k-1mAKAiA");
  }

  _getServeTime() async {
    final cache = await SharedPreferences.getInstance();
    String serveTime = cache.getString('serverTime') ?? '';
    time = int.parse(serveTime);
    DateTime date = DateTime.fromMillisecondsSinceEpoch(time);
    // dateTime = DateFormat('HH:mm').format(date);
  }

  _getMessagesInfo() async {
    EMMessage? emMessage = await widget.emMessage.latestMessage();

    body = emMessage?.body;
    if (body?.type == MessageType.TXT) {
      //文字
      textBody = body as EMTextMessageBody;
      content = textBody.content;
    }
    if (body?.type == MessageType.VOICE) {
      //音频
      voiceBody = body as EMVoiceMessageBody;
      content = voiceBody.remotePath!;
    }
    if (body?.type == MessageType.IMAGE) {
      //图片
      imageBody = body as EMImageMessageBody;
      content = imageBody.remotePath!;
    }
    if (body?.type == MessageType.VIDEO) {
      //视频
      videoBody = body as EMVideoMessageBody;
      content = videoBody.remotePath!;
    }
    if (kDebugMode) {
      // print('-------啊阿萨斯---------'+connt.content);
    }
    // setState(() {});
  }

  void _addChatListener() {
    // 添加收消息监听
    EMClient.getInstance.chatManager.addEventHandler(
      // EMChatEventHandler 对应的 key。
      "YXA6hl6vye2MTQOb2k-1mAKAiA",
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          player.setAsset('images/music_reveice.mp3');
          final session = await AudioSession.instance;
          session.configure(const AudioSessionConfiguration.music());
          player.play();
          for (var msg in messages) {
            switch (msg.body.type) {
              case MessageType.TXT:
                {
                  EMTextMessageBody body = msg.body as EMTextMessageBody;
                  EMClient.getInstance.chatManager.loadAllConversations();
                  EMClient.getInstance.chatManager.updateMessage(msg);
                  EMClient.getInstance.chatManager.getUnreadMessageCount();
                  _getMessagesInfo();
                  // emMessage?.latestMessage();
                  // widget.emMessage?.updateMessage(msg);

                  // _addLogToConsole(
                  //   "收到文字消息: ${body.content}, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.IMAGE:
                {
                  // _addLogToConsole(
                  //   "收到图片信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.VIDEO:
                {
                  // _addLogToConsole(
                  //   "收到视频信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.LOCATION:
                {
                  // _addLogToConsole(
                  //   "收到位置信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.VOICE:
                {
                  // _addLogToConsole(
                  //   "收到语音留言, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.FILE:
                {
                  // _addLogToConsole(
                  //   "收到图片信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.CUSTOM:
                {
                  // _addLogToConsole(
                  //   "接受自定义信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.CMD:
                {
                  // 当前回调中不会有 CMD 类型消息，CMD 类型消息通过 `EMChatEventHandler#onCmdMessagesReceived` 回调接收
                }
                break;
            }
          }
        },
      ),
    );
  }

  _getMemberInfo() async {
    final res = await Api.getInstance().getSessions(widget.emMessage.id);
    if (res['code'] == 0) {
      final data = res['data'];
      if (data != null) {
        setState(() {
          _userInfo = data;
          if (kDebugMode) {
            print('--------------' + _userInfo.toString());
          }
        });
      } else {
      }
    } else {
    }
  }

  Widget getMessageType(MessageType? type) {
    switch (type) {
      case MessageType.IMAGE:
        return Container(
          padding: const EdgeInsets.only(left: 8),
          child: const Text('[图片]'),
        );
        break;
      case MessageType.TXT:
        return Container(
          width: 180,
          margin: const EdgeInsets.only(left: 8),
          constraints: const BoxConstraints(maxWidth: 240),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(3.0)),
          child: Text(
            content,
            style: const TextStyle(
              color: Colors.black,
              fontSize: 14,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        );
        break;
      case MessageType.VOICE:
        return GestureDetector(
          onTap: () async {
          },
          child: Container(
            margin: const EdgeInsets.only(left: 8),
            child: const Text('[语音]'),
          ),
        );
        break;
    }
    return Container();
  }
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        widget.emMessage.markAllMessagesAsRead();
        unReadCont=0;
        messageListController.update([messageListController.listViewId]);
        if (widget.emMessage.id.isNotEmpty && _userInfo['owner'] != null) {
          if (RegExp(_regExp).firstMatch(widget.emMessage.id) != null) {
            Get.to(GroupChat(widget.emMessage.id, _userInfo['owner']),
                routeName: PageRouteNames.groupChatPage);
          } else {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (builder) => ChatPage(widget.emMessage.id)));
          }
        }
      },
      child: _userInfo.isNotEmpty
          ? Container(
        margin: const EdgeInsets.only(top: 5),
        padding: const EdgeInsets.only(
          top: 2.0,
          bottom: 5.0,
        ),
        decoration: const BoxDecoration(
          border: Border(
              bottom: BorderSide(color: Color(0xffEDEDED), width: 1)),
        ),
        child: Container(
          margin: const EdgeInsets.only(left: 16, right: 16),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                  margin: const EdgeInsets.all(5),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child: Image(
                        image: CachedNetworkImageProvider(
                            Provider.fixAvatar(_userInfo['photoUrl'])),
                        height: 45,
                        width: 45,
                        fit: BoxFit.fill),
                  )),
              Flexible(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          margin: const EdgeInsets.only(left: 8),
                          width: 200,
                          child: Text(
                            _userInfo['nickName'] ?? "",
                            style: const TextStyle(
                              color: Colors.black,
                              fontSize: 14,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Text(
                          dateTime,
                          style: const TextStyle(
                              fontSize: 14, color: Colors.grey),
                        ),
                      ],
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 5, left: 8),
                      child: Row(
                        mainAxisAlignment:
                        MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                padding: const EdgeInsets.only(
                                    left: 8,
                                    right: 8,
                                    top: 1,
                                    bottom: 1),
                                alignment: Alignment.center,
                                decoration: ShapeDecoration(
                                    shape: RoundedRectangleBorder(
                                      borderRadius:
                                      BorderRadius.circular(36),
                                    ),
                                    color: _userInfo['index'] >= 3
                                        ? const Color(0xffFE8A45)
                                        : _userInfo['index'] == 2
                                        ? ThemeColor.mainColor
                                        : ThemeColor.nanColor),
                                child: _userInfo['index'] >= 3
                                    ? IconText(
                                  _userInfo['index'].toString() ==
                                      'null'
                                      ? ' '
                                      : ' ${_userInfo['index'].toString()}',
                                  icon: const Icon(
                                      Icons.group_outlined,
                                      color: Colors.white),
                                  iconSize: 14,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                  ),
                                )
                                    : IconText(
                                  _userInfo['age'].toString() ==
                                      'null'
                                      ? ' 0'
                                      : ' ${_userInfo['age'].toString()}',
                                  icon: Icon(
                                      _userInfo['index'] == 2
                                          ? Icons.female
                                          : Icons.male,
                                      color: Colors.white),
                                  iconSize: 12,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                  ),
                                ),
                              ),
                              getMessageType(body?.type),
                            ],
                          ),
                          GetBuilder(
                            id: messageListController.listViewId,
                            builder: (MessageListController controller) {
                              return Visibility(
                                visible: unReadCont>0,
                                child: Container(
                                  padding: const EdgeInsets.only(
                                      left: 5, right: 5, top: 1, bottom: 1),
                                  decoration: BoxDecoration(
                                    color: Colors.red,
                                    borderRadius: const BorderRadius.all(
                                        Radius.circular(10.0)),
                                    border: Border.all(
                                        width: 1, color: Colors.white),
                                  ),
                                  child:  Text(
                                    unReadCont.toString(),
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 10),
                                  ),
                                ),
                              );
                            }
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      )
          : Container(),
    );
  }
}